package com.thiswhyme.sentinel.tokenserver;

import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.List;
import java.util.Properties;

/**
 * 从nacos上去获得动态的限流规则
 */
public class ClusterTokenServerInitFunc implements InitFunc {

    private final String remoteAddress="10.10.202.176";
    private final String namespace="b58f5675-6f17-47d0-b173-3bf416141ea0";
    private final String groupId="sentinel";
    private final String dataId="sentinel-cluster-param-flow";

    @Override
    public void init() throws Exception {
        Properties properties = new Properties();
        properties.put("serverAddr", remoteAddress);
        properties.put("namespace", namespace);

        ClusterFlowRuleManager.setPropertySupplier(namespeces->{
            ReadableDataSource<String, List<FlowRule>> rds =
                    new NacosDataSource<>(properties, groupId, dataId, source
                            -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
            return rds.getProperty();
        });
    }
}
